<template>
  <div class="tags-container">
    <van-button
        type="primary"
        color="#7232dd"
        plain
        class="edit-btn"
        @click="handleEdit"
    >
      编辑标签
    </van-button>

    <div class="tags-wrapper">
      <transition-group name="list" tag="div" class="tags-group">
        <van-tag
            v-for="(tag, index) in processedTags"
            :key="index"
            round
            :color="getTagColor(index)"
            text-color="#fff"
            class="tag-item"
        >
          {{ tag }}
        </van-tag>
      </transition-group>

      <van-empty
          v-if="processedTags.length === 0"
          image="search"
          description="暂无标签"
          class="empty-tips"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { getCurrentUser } from '../services/user';
import { showFailToast } from 'vant';

const router = useRouter();

// 响应式数据
const rawTags = ref<string[]>([]);
const processedTags = computed(() => {
  return rawTags.value
      .flatMap(tag =>
          tag.split(/\s+/) // 按连续空格分割
              .map(t => t.trim())
              .filter(t => t)
      );
});

// 颜色分配逻辑
const getTagColor = (index: number) => {
  const colors = ['#7232dd', '#07c160', '#1989fa', '#ff976a', '#ee0a24', '#9762e6'];
  return colors[index % colors.length];
};

// 深度解析函数（处理双重转义）
const parseDeepEscape = (input: string): string[] => {
  try {
    // 第一步：转义字符处理（处理 \\ 和 \"）
    let sanitized = input
        .replace(/\\u([0-9a-fA-F]{4})/gi, (_, match) => String.fromCharCode(parseInt(match, 16))) // 处理Unicode
        .replace(/\\\"/g, '"') // 转义双引号为普通双引号
        .replace(/^[\\"]+|[\"]+$/g, ""); // 去除首尾引号

    // 第二步：JSON解析
    const parsed = JSON.parse(sanitized);

    // 第三步：处理数组元素
    return Array.isArray(parsed)
        ? parsed.flatMap(item =>
            typeof item === 'string'
                ? item.split(/[\s,]+/) // 按空格/逗号分割
                    .map(t => t.trim())
                    .filter(t => t)
                : [String(item)]
        )
        : [String(parsed)];
  } catch (error) {
    console.error('解析失败:', error);
    return input
        .replace(/[\\"]/g, '') // 清除所有转义字符
        .split(/[\s,]+/)
        .map(t => t.trim())
        .filter(t => t);
  }
};

// 初始化加载
onMounted(async () => {
  try {
    const user = await getCurrentUser();
    if (user?.tags) {
      // 示例数据：输入 "[\"男\",\"php\"]"
      const parsed = parseDeepEscape(user.tags);
      rawTags.value = parsed;
      console.log('原始数据:', user.tags);
      console.log('解析结果:', rawTags.value);
    }
  } catch (error) {
    showFailToast('数据加载失败');
    console.error('初始化错误:', error);
  }
});


// 编辑操作
const handleEdit = () => {
  router.push({
    path: '/user/tags/edit',
    query: {
      tags: JSON.stringify(processedTags.value)
    }
  });
};

</script>

<style scoped>
/* 保持原有样式不变，添加必要的布局优化 */
.tags-container {
  padding: 16px;
  min-height: 60vh;
}

.tag-item {
  display: inline-block;
  margin: 4px;
  padding: 8px 16px;
  border-radius: 24px;
  font-size: 14px;
  transition: transform 0.2s ease;
  animation: slideIn 0.3s ease-out;
}

@keyframes slideIn {
  from {
    transform: translateX(20px);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}
</style>